package com.yhy.server.service;

import com.alibaba.fastjson.JSON;
import com.yhy.autoconfig.templates.HuanXinTemplate;
import com.yhy.domain.Question;
import com.yhy.domain.UserInfo;
import com.yhy.domain.mongo.RecommendUser;
import com.yhy.domain.vo.NearUserVo;
import com.yhy.domain.vo.PageResult;
import com.yhy.domain.vo.TodayBest;
import com.yhy.dubbo.api.QuestionApi;
import com.yhy.dubbo.api.UserInfoApi;
import com.yhy.dubbo.api.mongo.RecommendUserApi;
import com.yhy.dubbo.api.mongo.UserLocationApi;
import com.yhy.server.interceptor.UserHolder;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Reference
    private UserLocationApi userLocationApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity todayBest() {
        Long toUserId = UserHolder.getUserId();

        RecommendUser soulMate = recommendUserApi.findSoulMate(toUserId);
        //如果没有匹配任何人，则生成假数据
        if(soulMate == null){
            soulMate = new RecommendUser();
            soulMate.setUserId(1L);
            soulMate.setScore(99d);
        }
        UserInfo userInfo = userInfoApi.findById(soulMate.getUserId());

        TodayBest todayBest = TodayBest.init(userInfo, soulMate);

        return ResponseEntity.ok(todayBest);
    }

    public ResponseEntity recommendation(Integer page, Integer pagesize) {

        Long toUserId = UserHolder.getUserId();

        //根据toUserId找出封装了RecommendUser数据的pageResult
        PageResult pageResult = recommendUserApi.queryRecommendUserList(page,pagesize,toUserId);

        //判断pageResult 如为空或总数为0 则使用defaultUser()创建假数据
        if(pageResult == null || pageResult.getCounts() == 0){
            pageResult = new PageResult(page,pagesize,10,defaultUser());
        }

        //根据已有的pageResult去查询UserInfo,并开始构建返回值
        List<RecommendUser> items = (List<RecommendUser>) pageResult.getItems();
        List<TodayBest> todayBestList = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo userInfo = userInfoApi.findById(item.getUserId());
            TodayBest todayBest = TodayBest.init(userInfo, item);
            todayBestList.add(todayBest);
        }
        //将原有pageResult里的List<RecommendUser>替换成List<TodayBest> 正好满足了返回数据的要求 同时也不需要新建List
        pageResult.setItems(todayBestList);
        return ResponseEntity.ok(pageResult);
    }

    public List<RecommendUser> defaultUser(){
        List<RecommendUser> defaultUsers = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(10L+i);
            recommendUser.setScore(75d+i);
            defaultUsers.add(recommendUser);
        }
        return defaultUsers;
    }

    /**
     * 查看佳人详情
     * (首页点击缩略图查看用户详情)
     * @param userId
     * @return
     */
    public ResponseEntity personalInfo(Long userId) {
//        1.查看用户详情
        UserInfo userInfo = userInfoApi.findById(userId);
//        2.获取用户的fateValue 从recommendUser表
        RecommendUser recommendUser = recommendUserApi.findRecommendUser(userId,UserHolder.getUserId());
//        3.把userInfo和recommendUser封装成vo对象TodayBest
        TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
//        4.返回
        return ResponseEntity.ok(todayBest);
    }

    /**
     * 查看陌生人问题
     * (查看用户的好友问题)
     * @param userId
     * @return
     */
    public ResponseEntity strangerQuestions(Long userId) {
        Question question = questionApi.findQuestionByUid(userId);
        //判断
        String text = question == null? "你喜欢CF还是LOL?":question.getTxt();

        return ResponseEntity.ok(text);
    }

    /**
     * 回答陌生人问题
     * 封装四个参数到map 转json返回即可
     * 四个参数为: 当前用户userId,当前用户nickname,对方用户陌生人问题strangerQuestions,以及本次回答文本reply
     * {"userId": "1","nickname":"黑马小妹","strangerQuestion": "","reply": ""}
     * @param userId
     * @param reply
     * @return
     */
    public ResponseEntity answerStrangerQuestion(Long userId, String reply) {
//        1.首先构造消息体 因为环信发送的数据是Json 提前准备数据
//        1.1获取自己的userinfo
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
//        1.2获取对方的陌生人问题
        Question question = questionApi.findQuestionByUid(userId);
//        1.3数据封装map 方便转json传递
        Map map = new HashMap();
        map.put("userId",userInfo.getId().toString());
        map.put("nickname",userInfo.getNickname());
        String text = question == null? "你喜欢java还是php?":question.getTxt();
        map.put("strangerQuestion",text);
        map.put("reply",reply);

//        1.4map转json
        String json = JSON.toJSONString(map);

//        2.使用环信模板发送信息
        huanXinTemplate.sendMsg(userId.toString(),json);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity searchNear(String gender, String distance) {
        //1.获取当前用户id
        Long userId = UserHolder.getUserId();
        //2.调用api返回附近所有用户id数组
        List<Long> userIds = userLocationApi.searchNear(userId,distance);
//        2.1封装vo对象
        List<NearUserVo> list =new ArrayList<>();
        for (Long id : userIds) {
            //3.排除自己后查询用户详情
            if(userId.equals(id)){
                continue;
            }
            UserInfo userInfo = userInfoApi.findById(id);
            //4.性别筛选
            if(gender != null && !userInfo.getGender().equals(gender)){
                continue;
            }
            NearUserVo vo = NearUserVo.init(userInfo);
            list.add(vo);
        }
        //5.返回
        return ResponseEntity.ok(list);
    }
}
